package com.th.common.utils.regex;


import com.th.common.exception.UtilException;

import java.util.regex.Pattern;

/**
 * 字段验证器（验证器），分两种类型的验证：
 *
 * <ul>
 *     <li>isXXX：通过返回boolean值判断是否满足给定格式。</li>
 *     <li>validateXXX：通过抛出客户端异常{@link UtilException}检查是否满足给定格式。</li>
 * </ul>
 * 参考自：cn.hutool.core.lang.Validator
 *
 * @author hutool
 */
public class Validator {

    public static boolean isMobile(CharSequence value) {
        return isMatchRegex(PatternPool.MOBILE, value);
    }


    public static boolean validateMobile(String value) {
        if (!isMobile(value)) {
            throw new UtilException("手机格式错误");
        }

        return true;
    }

    public static boolean isEmail(CharSequence value) {
        return isMatchRegex(PatternPool.EMAIL, value);
    }

    public static boolean validateEmail(String value) {
        if (!isEmail(value)) {
            throw new UtilException("邮箱格式错误");
        }

        return true;
    }

    /**
     * 是不是符合用户系统的账号格式
     * 账号格式可以为邮箱或手机号
     *
     * @param value 账号
     */
    public static boolean isAccount(CharSequence value) {
        return Validator.isEmail(value) || Validator.isMobile(value);
    }

    public static boolean validateAccount(CharSequence value) {
        if (!isAccount(value)) {
            throw new UtilException("账号格式错误");
        }

        return true;
    }

    public static boolean validateNickname(CharSequence value) {
        if (!isMatchRegex(PatternPool.NICKNAME, value)) {
            throw new UtilException("用户名格式错误");
        }

        return true;
    }

    public static boolean isUrl(CharSequence value) {
        return isMatchRegex(PatternPool.URL, value);
    }

    public static boolean isMatchRegex(Pattern pattern, CharSequence value) {
        if (value == null || pattern == null) {
            return false;
        }
        return pattern.matcher(value).matches();
    }
}
